-module(random_distribution).
-export([run/0]).
%%% kafka 分区随机算法的测试
run() ->
    % Initialize counters for 0-11
    Counters = lists:duplicate(12, 0),
    % Generate 100,000 random numbers
    FinalCounters = generate_numbers(100000, Counters),
    % Print distribution results
    print_distribution(FinalCounters, 0).

generate_numbers(0, Counters) -> Counters;
generate_numbers(N, Counters) ->
    % Generate random number (0-11)
    RandomNum = rand:uniform(12) - 1,
    % Update counter (1-based index: position = RandomNum + 1)
    Updated = update_counter(RandomNum + 1, Counters),
    generate_numbers(N - 1, Updated).

update_counter(Index, Counters) ->
    OldCount = lists:nth(Index, Counters),
    NewCount = OldCount + 1,
    replace_nth(Index, NewCount, Counters).

replace_nth(1, Value, [_|T]) -> [Value|T];
replace_nth(I, Value, [H|T]) -> [H|replace_nth(I-1, Value, T)].

print_distribution([], _) -> ok;
print_distribution([H|T], Num) ->
    Percentage = (H / 100000) * 100,
    io:format("Number ~2w: ~6w occurrences (~.2f%)~n", [Num, H, Percentage]),
    print_distribution(T, Num + 1).